package com.uziot.activiti6.controller;

import com.uziot.activiti6.common.util.Result;
import com.uziot.activiti6.controller.vo.GroupRequest;
import com.uziot.activiti6.controller.vo.MembershipRequest;
import com.uziot.activiti6.controller.vo.UserRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className FlowUserProvider
 * @date 2021-02-26 10:38:41
 * @description
 */

@RestController
@Slf4j
@Api(tags = "流程-用户和用户组配置")
@RequestMapping(value = {"/api/flowUser"})
public class FlowUserController {

    @Autowired
    IdentityService identityService;

    /***
     * 新增组
     * @param groupRequest groupRequest
     */
    @PostMapping(value = "/newGroup")
    @ApiOperation(value = "新增用户组", notes = "新增用户组")
    public Result newGroup(@RequestBody @ApiParam(value = "新增用户组请求") @Valid GroupRequest groupRequest) {
        try {
            if (StringUtils.isBlank(groupRequest.getName())) {
                return Result.error(-1, "用户组名称不能为空");
            }
            //验证是否保存成功
            Group groupInDb = identityService.createGroupQuery().groupId(groupRequest.getId()).singleResult();
            if (groupInDb != null) {
                return Result.error(-2, "ID已存在");
            }
            Group group = identityService.newGroup(groupRequest.getId());
            group.setName(groupRequest.getName());
            group.setType("assignment");
            //保存用户组
            identityService.saveGroup(group);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @PostMapping(value = "/deleteGroup")
    @ApiOperation(value = "删除用户组", notes = "删除用户组")
    public Result deleteGroup(@RequestBody @ApiParam(value = "新增用户组ID") @Valid GroupRequest groupRequest) {
        try {
            identityService.deleteGroup(groupRequest.getId());
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @PostMapping(value = "/newUser")
    @ApiOperation(value = "新增用户", notes = "新增用户")
    public Result newUser(@RequestBody @ApiParam(value = "新增用户请求对象") @Valid UserRequest userRequest) {
        try {
            // 验证是否保存成功
            User userInDb = identityService.createUserQuery().userId(userRequest.getId()).singleResult();
            if (userInDb != null) {
                return Result.error(-2, "用户ID已存在");
            }
            User user = identityService.newUser(userRequest.getId());
            user.setEmail(userRequest.getEmail());
            user.setFirstName(userRequest.getFirstName());
            user.setLastName(userRequest.getLastName());
            user.setPassword(userRequest.getPassword());
            identityService.saveUser(user);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }


    @PostMapping(value = "/deleteUser")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    public Result deleteUser(@RequestBody @ApiParam(value = "删除用户请求对象") @Valid UserRequest userRequest) {
        try {
            identityService.deleteUser(userRequest.getId());
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @PostMapping(value = "/createMembership")
    @ApiOperation(value = "新增用户与组关联", notes = "新增用户与组关联")
    public Result createMembership(@RequestBody @ApiParam(value = "用户与组关联请求对象") @Valid MembershipRequest membershipRequest) {
        try {
            String userId = membershipRequest.getUserId();
            User userInDb = identityService.createUserQuery().userId(userId).singleResult();
            if (userInDb == null) {
                return Result.error(-2, "用户ID不存在");
            }
            //验证是否保存成功
            String groupId = membershipRequest.getGroupId();
            Group groupInDb = identityService.createGroupQuery().groupId(groupId).singleResult();
            if (groupInDb == null) {
                return Result.error(-2, "用户组ID不存在");
            }
            long count = identityService.createUserQuery().userId(userId).memberOfGroup(groupId).count();
            if (count > 0) {
                return Result.error(-2, "用户与组关联ID已存在");
            }
            identityService.createMembership(userId, groupId);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }


    @PostMapping(value = "/deleteMembership")
    @ApiOperation(value = "删除用户与组关联", notes = "删除用户与组关联")
    public Result deleteMembership(@RequestBody @ApiParam(value = "用户与组关联请求对象") @Valid MembershipRequest membershipRequest) {
        try {
            String userId = membershipRequest.getUserId();
            String groupId = membershipRequest.getGroupId();
            identityService.deleteMembership(userId, groupId);
            return Result.ok();
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }


    @GetMapping(value = "/selectAllUsers")
    @ApiOperation(value = "查询所有用户", notes = "查询所有用户")
    public Result selectAllUsers() {
        try {
            List<User> list = identityService.createUserQuery().list();
            return Result.ok().put("list", list);
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @GetMapping(value = "/selectAllGroups")
    @ApiOperation(value = "查询所候选组", notes = "查询所候选组")
    public Result selectAllGroups() {
        try {
            List<Group> list = identityService.createGroupQuery().list();
            return Result.ok().put("list", list);
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @GetMapping(value = "/selectUser")
    @ApiOperation(value = "根据用户名查询用户", notes = "根据用户名查询用户")
    public Result selectUser(@RequestParam String username) {
        try {
            User user = identityService.createUserQuery().userId(username).singleResult();
            //查询user1所属于的组
            List<Group> groupsForUser = identityService.createGroupQuery().groupMember(username).list();
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("user", user);
            result.put("groups", groupsForUser);
            return Result.ok().put("result", result);
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }

    @GetMapping(value = "/selectGroup")
    @ApiOperation(value = "根据用户名查询用户", notes = "根据用户名查询用户")
    public Result selectGroup(@RequestParam String groupName) {
        try {
            //查询属于组group1的用户
            List<User> usersInGroup = identityService.createUserQuery().memberOfGroup(groupName).list();
            // 查询组相关信息
            Group group = identityService.createGroupQuery().groupId(groupName).singleResult();
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("group", group);
            result.put("users", usersInGroup);
            return Result.ok().put("result", result);
        } catch (Exception e) {
            return Result.error(-1, e.getMessage());
        }
    }
}
